package com.cg.servlet;

import com.cg.pojo.User;
import com.cg.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/user/add")
public class AddUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用post请求获取用户信息
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setPassword(req.getParameter("password"));
        user.setRole(req.getParameter("role"));
        user.setSex(Integer.parseInt(req.getParameter("sex")));
        user.setAge(Integer.parseInt(req.getParameter("age")));


        UserService service=new UserService();
        int result=service.add(user);
        String msg="";
        if (result == 1) {
            //如果新增成功，则重定向到学生列表
            resp.sendRedirect(req.getContextPath() + "/user/list");
        } else {
            //如果新增失败，则给与用户详细的提示信息
            if (result == -1) {
                msg = "用户编号已存在";
            } else {
                msg = "新增用户失败";
            }
            req.setAttribute("msg", msg);
            req.getRequestDispatcher("/addUser.jsp").forward(req, resp);
        }
    }
}
